package com.detrum.sportcamera;

import android.Manifest;
import android.content.ComponentName;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.ServiceConnection;
import android.content.pm.PackageManager;
import android.graphics.drawable.Drawable;
import android.os.Build;
import android.os.Bundle;

import com.detrum.base.BaseActivity;

import com.detrum.base.BaseFinal;
import com.detrum.base.BaseStatic;
import com.detrum.base.ServiceStatic;
import com.detrum.bean.FileBean;
import com.detrum.bean.FileBeanAll;
import com.detrum.myijkplayer.activities.VideoActivity;
import com.detrum.myijkplayer.widget.media.MyVideoView;
import com.detrum.costomview.BaseTitle;

import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.support.annotation.NonNull;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.KeyEvent;
import android.view.View;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.detrum.sportcamera.adapter.NfsRefreshAdapter;
import com.detrum.sportcamera.finals.SportStatic;
import com.detrum.sportcamera.service.WifiService;
import com.detrum.sportcamera.service.WifiServiceCallback4;
import com.detrum.sportcamera.service.WifiServiceCallback6;
import com.detrum.sportcamera.service.WifiServiceCallback7;
import com.detrum.sqlite.SqliteMediaOperation;
import com.detrum.swipe.BaseRecyclerAdapter;
import com.detrum.swipe.OnLoadMoreListener;
import com.detrum.swipe.OnRefreshListener;
import com.detrum.swipe.SuperRefreshRecyclerView;
import com.detrum.utils.LogUtils;
import com.detrum.utils.MyMethod;
import com.detrum.utils.NfsUtil;
import com.detrum.utils.PermissionCall;
import com.detrum.utils.PermissionRegister;
import com.google.gson.Gson;

import android.widget.LinearLayout;

import java.io.File;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Vector;

import tv.danmaku.ijk.media.player.IMediaPlayer;
import tv.danmaku.ijk.media.player.IjkMediaPlayer;

public class NfsActivity2 extends BaseActivity implements OnRefreshListener,OnLoadMoreListener,View.OnClickListener,PermissionCall {

    private Context context;
    private final String TAG = "NfsActivity2";

    private MyVideoView thumb;
    private BaseTitle nfsTitle;
    private ProgressBar progressBar;
    private TextView noFilesTv;
    private SuperRefreshRecyclerView refreshView;
    private TextView toastTv;
    private LinearLayout bottomLocal;
    private TextView selectAllLocal;
    private TextView downloadTv;
    private TextView deleteLocal;
    private TextView cancelLocal;

    private GridLayoutManager manager;
    private boolean isResume;
    private ArrayList<FileBean> beanList;
    private PermissionRegister permissionRegister;
    private NfsRefreshAdapter nfsRefreshAdapter;

    private WifiService wifiService;
    private Intent wifiIntent;
    private WifiConn wifiConn;

    private int first;
    private boolean isSelectAll, isEdit;
    private Vector<FileBean> videoNfs;
    private boolean isLoadingThumb,isImageLoadFinish;
    private String videoLoadName,imageLoadName;

    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if (msg.what == 100) {
                if(isResume){
                    toastTv.setVisibility(View.GONE);
                    if(msg.arg1>=first&&msg.arg1<first+6&& msg.arg1 < beanList.size()){
                        nfsRefreshAdapter.notifyItemChanged(msg.arg1);
                    }
                }
            }
        }
    };

    private WifiServiceCallback4 wifiServiceCallback4 = new WifiServiceCallback4() {
        @Override
        public void firstList(FileBean bean) {
            if(isResume){
                noFilesTv.setVisibility(View.GONE);
                toastTv.setText(bean.getFileName()+getResources().getString(R.string.data_syn));
                toastTv.setVisibility(View.VISIBLE);
            }
        }

        @Override
        public void connectFail() {
            if(isResume){
                toastTv.setVisibility(View.GONE);
                //MyMethod.ShowDiaLogFinish(NfsActivity2.this,"获取设备文件失败");
            }
        }

        @Override
        public void emptyList() {
            noFilesTv.setVisibility(View.VISIBLE);
        }

        @Override
        public void fileListFinish(ArrayList<FileBean> fileBeans) {
            if(isResume){
                noFilesTv.setVisibility(View.GONE);
                toastTv.setText(R.string.data_syn_finish);
                handler.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        toastTv.setVisibility(View.GONE);
                    }
                },1000);
            }
            handler.postDelayed(new Runnable() {
                @Override
                public void run() {
                    wifiService.NfsRefresh(1);
                }
            }, 1000);
        }

        @Override
        public void refreshList(ArrayList<FileBean> fileBeans) {
            LogUtils.e(TAG+"---refreshList---"+fileBeans.size());
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    refreshView.setRefreshing(false);
                }
            });
            if (fileBeans == null || fileBeans.size() == 0) {
                return;
            }
            //写入position信息

            for (int i = 0; i < fileBeans.size(); i++) {
                fileBeans.get(i).setPosition(i);
                LogUtils.e(TAG+"---refreshList---"+fileBeans.get(i).getFileName()+"----"+fileBeans.get(i).getPosition());
            }
            if (beanList == null) {
                beanList = new ArrayList<>();
                beanList.addAll(fileBeans);
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        if(isResume){
                            initAdapter();
                            if (SportStatic.isGetFiles) {
                                wifiService.loadNfsSingle(beanList);
                                wifiService.cleanCache();
                            }
                        }
                    }
                });
            } else {
                beanList.clear();
                beanList.addAll(fileBeans);
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        if(isResume){
                            cancelBottom();
                        }
                        if (SportStatic.isGetFiles) {
                            wifiService.loadNfsSingle(beanList);
                            wifiService.cleanCache();
                        }
                    }
                });
            }

        }

        @Override
        public void moreList(final ArrayList<FileBean> fileBeans) {
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    refreshView.setLoadingMore(false);
                }
            });
            if (beanList == null || fileBeans == null || fileBeans.size() == 0) {
                return;
            }
            int oldSize = beanList.size();
            for (int i = 0; i < fileBeans.size(); i++) {
                fileBeans.get(i).setPosition(oldSize + i);
            }
            beanList.addAll(fileBeans);
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    wifiService.loadNfsSingle(fileBeans);
                    if(isResume){
                        nfsRefreshAdapter.notifyDataSetChanged();
                    }
                }
            });
        }

        @Override
        public void singleImageStart(final FileBean fileBean) {
            isImageLoadFinish = false;
            if(isResume){
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        imageLoadName = fileBean.getFileName();
                        text = getResources().getString(R.string.loading2)+imageLoadName;
                        toastTv.setText(text);
                        toastTv.setVisibility(View.VISIBLE);
                    }
                });
            }

        }

        @Override
        public void singleItem(final FileBean fileBean, final int position) {
            LogUtils.e(TAG+"----"+fileBean.getFileName()+"---"+position);
            if (NfsUtil.isVideoFile(fileBean.getFileName()) && (fileBean.getThumbPath() == null || fileBean.getThumbPath().length()==0||fileBean.getTime() == null)) {
                videoNfs.add(fileBean);
                if (!isLoadingThumb && isResume) {
                    LogUtils.e(TAG+"--loading--"+fileBean.getFileName());
                    LoadVideoThumb();
                }
                return;
            }
            LogUtils.e(TAG+"--refresh--"+fileBean.getFileName()+"---"+position);
            if (position == 0) {
                handler.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        if (position >= first && position < first + 6) {
                            beanList.get(position).setCachePath(fileBean.getCachePath());
                            beanList.get(position).setThumbPath(fileBean.getThumbPath());
                            if(isResume){
                                nfsRefreshAdapter.notifyItemChanged(position);
                            }
                        }
                    }
                }, 1000);
            } else {
                if (position >= first && position < first + 6 && position < beanList.size()) {
                    beanList.get(position).setCachePath(fileBean.getCachePath());
                    beanList.get(position).setThumbPath(fileBean.getThumbPath());
                    if(isResume){
                        nfsRefreshAdapter.notifyItemChanged(position);
                    }
                }
            }
        }

        @Override
        public void singleLoadFinish() {
            isImageLoadFinish = true;
            if(isResume){
                if(!isLoadingThumb){
                    toastTv.setVisibility(View.GONE);
                }else{
                    text = getResources().getString(R.string.loading2)+videoLoadName;
                    toastTv.setText(text);
                }
            }
        }

        @Override
        public void timeout() {
            if (isResume) {
                MyMethod.ShowDiaLogFinish(NfsActivity2.this, R.string.connect_timeout);
            }
            wifiService.stopNfsDownload();
            SportStatic.isLoginPre = false;
            ServiceStatic.isWifiDeviceConnect = false;
        }
    };

    private WifiServiceCallback6 wifiServiceCallback6 = new WifiServiceCallback6() {
        @Override
        public void indexFail() {
            if (isResume) {
                toastTv.setText(getResources().getString(R.string.download_fail));
                toastTv.setVisibility(View.VISIBLE);
                handler.postDelayed(new ToastHide(), 800);
            }
        }

        @Override
        public void finishAll() {
            if (isResume) {
                toastTv.setVisibility(View.GONE);
            }
        }

        @Override
        public void itemStart(String fileName,String num) {
            if (isResume) {
                text = getResources().getString(R.string.downloadStart) + " " + fileName;
                toastTv.setText(text);
                Drawable drawable = getResources().getDrawable(R.drawable.ic_close_black_24dp);
                drawable.setBounds(0,0,drawable.getMinimumWidth(),drawable.getMinimumHeight());
                toastTv.setCompoundDrawables(null,null,drawable,null);
                toastTv.setCompoundDrawablePadding(10);
                toastTv.setVisibility(View.VISIBLE);
                toastTv.setOnClickListener(NfsActivity2.this);
            }
        }

        @Override
        public void itemComplete(String fileName,String num, int size) {
            if (isResume) {
                if(fileName.endsWith(".mp4")){
                    if(SportStatic.countSize!=0){
                        text = getResources().getString(R.string.downloadComplete) + " " + fileName+"("+num+" "+size*100l/SportStatic.countSize+"%)";
                    }else{
                        text = getResources().getString(R.string.downloadComplete) + " " + fileName;
                    }
                    toastTv.setText(text);
                    toastTv.setVisibility(View.VISIBLE);
                }else if(fileName.endsWith(".jpg")){
                    text = getResources().getString(R.string.downloadComplete) + " " + fileName;
                    toastTv.setText(text);
                    toastTv.setVisibility(View.VISIBLE);
                }
            }
        }

        @Override
        public void itemFail(String fileName) {

        }

        @Override
        public void countSize(int countSize) {
            SportStatic.countSize = countSize;
        }

        @Override
        public void itemVideoSize(String fileName,String num, int size) {
            if (isResume) {
                if (toastTv.getVisibility() == View.GONE) {
                    Drawable drawable = getResources().getDrawable(R.drawable.ic_close_black_24dp);
                    drawable.setBounds(0,0,drawable.getMinimumWidth(),drawable.getMinimumHeight());
                    toastTv.setCompoundDrawables(null,null,drawable,null);
                    toastTv.setCompoundDrawablePadding(10);
                    toastTv.setVisibility(View.VISIBLE);
                    toastTv.setOnClickListener(NfsActivity2.this);
                }
                if(SportStatic.countSize!=0){
                    text = getResources().getString(R.string.downloadStart) + " " + fileName+"("+num+" "+size*100l/SportStatic.countSize+"%)";
                    toastTv.setText(text);
                }
            }
        }

        @Override
        public void reDownload(final String fileName, final File file) {
            LogUtils.i("reDownload fileName = "+fileName);

            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    new AlertDialog.Builder(context,R.style.loading_dialog)
                            .setMessage(R.string.redownload)
                            .setNegativeButton(R.string.jixu, new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog, int which) {
                                    FileBean fileBean = SqliteMediaOperation.getInstence(context).SelectSingle(fileName);
                                    if(fileBean!=null){
                                        fileBean.setSelect(true);
                                        wifiService.downloadNfsList(fileBean);
                                    }
                                    dialog.dismiss();
                                }
                            })
                            .setPositiveButton(R.string.exit, new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog, int which) {
                                    if(file!=null){
                                        file.delete();
                                    }
                                    dialog.dismiss();
                                }
                            })
                            .create()
                            .show();
                }
            });

        }
    };

    private WifiServiceCallback7 wifiServiceCallback7 = new WifiServiceCallback7() {
        @Override
        public void indexFail() {

        }

        @Override
        public void itemComplete(String fileName) {
            toastTv.setText(fileName+getResources().getString(R.string.delete_item));
            toastTv.setVisibility(View.VISIBLE);
        }

        @Override
        public void itemFail(String fileName) {

        }

        @Override
        public void finishAll() {
            if (isResume) {
                bottomLocal.setVisibility(View.GONE);
                isEdit = false;
                nfsRefreshAdapter.setEdit(isEdit);
                toastTv.setText(R.string.delete_finish);
                handler.postDelayed(new ToastHide(),1000);
                onRefresh();
            }
        }
    };

    @Override
    public boolean onKeyUp(int keyCode, KeyEvent event) {
        if(keyCode== KeyEvent.KEYCODE_BACK){
            if(isEdit){
                cancelBottom();
            }else{
                finish();
            }
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    private void cancelBottom(){
        bottomLocal.setVisibility(View.GONE);
        isSelectAll = false;
        isEdit = false;
        nfsRefreshAdapter.setEdit(isEdit);
        nfsRefreshAdapter.notifyDataSetChanged();
    }

    @Override
    public void onClick(View v) {
        if(v == cancelLocal){
            if(isResume){
                cancelBottom();
            }
        }else if(v == deleteLocal){
            ArrayList<FileBean> list = new ArrayList<>();
            for (int i = 0; i < beanList.size(); i++) {
                if (beanList.get(i).isSelect()) {
                    list.add(beanList.get(i));
                }
            }
            if (list.size() == 0) {
                return;
            }
            LogUtils.i("delete size = " + list.size());
            FileBean[] fileBeans = new FileBean[list.size()];
            fileBeans = list.toArray(fileBeans);
            LogUtils.i("delete fileBeans = " + fileBeans[0].getFileName());
            if (SportStatic.isDownloading) {
                wifiService.stopNfsDownload();
            }
            wifiService.setWifiServiceCallback7(wifiServiceCallback7);
            wifiService.deleteNfsList(fileBeans);
        }else if(v == selectAllLocal){
            if (isSelectAll) {
                for (int i = 0; i < beanList.size(); i++) {
                    beanList.get(i).setSelect(false);
                }
                selectAllLocal.setText(R.string.noall);
                isSelectAll = false;
            } else {
                for (int i = 0; i < beanList.size(); i++) {
                    beanList.get(i).setSelect(true);
                }
                isSelectAll = true;
                selectAllLocal.setText(R.string.all);
            }
            if(isResume){
                nfsRefreshAdapter.notifyDataSetChanged();
            }
        }else if(v == downloadTv){
            if(isResume){
                cancelBottom();
            }
            isEdit = false;
            ArrayList<FileBean> list = new ArrayList<>();
            for (int i = 0; i < beanList.size(); i++) {
                if (beanList.get(i).isSelect()) {
                    list.add(beanList.get(i));
                }
            }
            if (list.size() == 0) {
                return;
            }
            LogUtils.e("download list size = " + list.size());
            FileBean[] fileBeans = new FileBean[list.size()];
            fileBeans = list.toArray(fileBeans);
            wifiService.downloadNfsList(fileBeans);
        }else if(v == toastTv){
            new AlertDialog.Builder(context,R.style.loading_dialog)
                    .setMessage(R.string.download_cancel)
                    .setNegativeButton(R.string.delete, new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            dialog.dismiss();
                            wifiService.stopAnddeleteDownload();
                        }
                    })
                    .setPositiveButton(R.string.cancel, new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            dialog.dismiss();
                        }
                    })
                    .create()
                    .show();
        }
    }

    @Override
    public void onRefresh() {
        //刷新后会重写position信息，这里必须停止单项加载
        wifiService.stopNfsSingle();
        if(videoNfs!=null){
            videoNfs.clear();
        }
        //正在首次进入同步中不能刷新,首次列表获取完成，查询标志1
        LogUtils.e(TAG+"---"+SportStatic.isGetFiles);
        if (SportStatic.isGetFiles) {
            wifiService.NfsRefresh(1);
        } else {
            refreshView.setRefreshing(false);
            toastTv.setText(R.string.device_syn);
            toastTv.setVisibility(View.VISIBLE);
            handler.postDelayed(new ToastHide(),800);
        }
    }

    @Override
    public void onLoadMore() {
        if (SportStatic.isGetFiles) {
            wifiService.NfsLoadMore(1);
        } else {
            refreshView.setLoadingMore(false);
            toastTv.setText(R.string.device_syn);
            toastTv.setVisibility(View.VISIBLE);
            handler.postDelayed(new ToastHide(),800);
        }
    }

    @Override
    public void ScanWifi() {

    }

    @Override
    public void startUsbPreview() {

    }

    @Override
    public void startPreview() {

    }

    @Override
    public void getVersion(VerFlag flag) {
        if(flag == VerFlag.MAIN){
            connectService();
        }
    }

    @Override
    public void Cancel() {

    }

    private class WifiConn implements ServiceConnection {

        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            wifiService = ((WifiService.WifiBinder) service).getService();
            wifiService.setWifiServiceCallback4(wifiServiceCallback4);
            wifiService.setWifiServiceCallback6(wifiServiceCallback6);
            if(ServiceStatic.isWifiDeviceConnect){
                if (SportStatic.isGetFiles) {
                    /**
                     * 连接状态保持下，设备列表完全读取一次后，查询标志为1
                     * 设备连接断开时，设备列表读取标志设为false,同时需要修改数据库标志
                     */
                    if(!SportStatic.isNfsRestart){
                        wifiService.NfsRefresh(1);
                    }
                } else {
                    /**
                     * 列表没有加载完成
                     * 先查询先前退出时的标志2
                     * 然后启动设备媒体文件列表加载（可能为空--没有数据 或 数据很少 或 上次已加载大部分本次数据很少）
                     * 该状态下获取的列表不能点击
                     * 加载时，下方toast同步显示正在加载的文件名
                     */
                    wifiService.NfsRefresh(2);
                    wifiService.getNfsList();
                }
            }
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {
        }
    }

    /**
     * 下方toastTest定时隐藏
     */
    private class ToastHide implements Runnable {
        @Override
        public void run() {
            if (isResume) {
                toastTv.setText("");
                toastTv.setVisibility(View.GONE);
            }
        }
    }

    /**
     * 下载提示
     */
    String text;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_nfs2);
        context = this;
        permissionRegister = new PermissionRegister(this);
        initView();
    }

    @Override
    protected void onStart() {
        super.onStart();
        LogUtils.i("NfsActivity2 onStart");
    }

    @Override
    protected void onRestart() {
        super.onRestart();
        SportStatic.isNfsRestart = true;
        LogUtils.i("NfsActivity2 onRestart");
    }

    /**
     * resume中进行Service绑定
     */
    @Override
    protected void onResume() {
        super.onResume();
        isResume = true;
        if(ServiceStatic.isWifiDeviceConnect){
            if(Build.VERSION.SDK_INT>=Build.VERSION_CODES.M){
                permissionRegister.CheckPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE, R.string.sdcard_msg, 1, this);
            }else{
                getVersion(VerFlag.MAIN);
            }
        }else{
            finish();
        }
    }

    /**
     * 暂停时停止列表获取，停止删除，停止单项加载（清空加载列表，释放视频加载资源，释放图片加载资源），解绑服务
     * 停止列表获取是为了保障下次进入时，不会开启多个列表获取线程。
     * 停止删除是为了保障图片预览或视频播放不冲突。（不会突然出现文件不存在的空指针）
     * 停止加载项目是为了保障正常的播放，图片显示。（同一文件只有一个线程或程序访问）
     */
    @Override
    protected void onPause() {
        super.onPause();
        isResume = false;
        if(videoNfs!=null){
            videoNfs.clear();
        }
        thumb.release(true);
        disconnectService();
    }

    @Override
    protected void onStop() {
        super.onStop();
        LogUtils.i("NfsActivity2 onStop");
    }

    @Override
    protected void onDestroy() {
        SportStatic.isNfsRestart = false;
        super.onDestroy();
    }

    /**
     * service绑定
     */
    private void connectService() {
        wifiIntent = new Intent(context, WifiService.class);
        wifiConn = new WifiConn();
        bindService(wifiIntent, wifiConn, BIND_AUTO_CREATE);
    }

    /**
     * service解绑，及解绑前的各种停止加载项目
     */
    private void disconnectService(){
        if(wifiService!=null){
            wifiService.stopGetList();
            wifiService.stopNfsSingle();
            //wifiService.stopNfsDownload();
            wifiService.stopNfsDelete();
        }
        if(wifiConn!=null){
            unbindService(wifiConn);
            wifiConn=null;
        }
    }

    private void LoadVideoThumb() {
        isLoadingThumb = true;
        handler.post(videoThumb);
    }

    private Runnable videoThumb = new Runnable() {
        @Override
        public void run() {
            LogUtils.i("remove size = " + videoNfs.size());
            if (videoNfs.size() == 0) {
                if(isResume){
                    if(isImageLoadFinish){
                        toastTv.setVisibility(View.GONE);
                    }else{
                        text = getResources().getString(R.string.loading2)+imageLoadName;
                        toastTv.setText(text);
                    }
                }
                isLoadingThumb = false;
                return;
            }
            FileBean fileBean = videoNfs.remove(0);
            getVideoThumb(fileBean);
        }
    };

    private void getVideoThumb(final FileBean fileBean) {
        isLoadingThumb = true;
        String nfsPath = "nfs://" + BaseStatic.DHCP_SERVICE_IP + "/sdcard?" + fileBean.getNfsPath();
        videoLoadName = fileBean.getFileName();
        final int position = fileBean.getPosition();
        IjkMediaPlayer.loadLibrariesOnce(null);
        IjkMediaPlayer.native_profileBegin("libijkplayer.so");
        if(isResume){
            text = getResources().getString(R.string.loading2)+videoLoadName;
            toastTv.setText(text);
            toastTv.setVisibility(View.VISIBLE);
            thumb.setCaptureComplete(new MyVideoView.CaptureComplete() {
                @Override
                public void complete(String thumbPath) {
                    beanList.get(position).setTime(paserTime(thumb.getDuration()));
                    beanList.get(position).setThumbPath(thumbPath);
                    if (position >= first && position < first + 6) {
                        Message message = new Message();
                        message.what = 100;
                        message.arg1 = position;
                        handler.sendMessage(message);
                    }
                    thumb.release(true);
                    if(isResume){
                        handler.postDelayed(videoThumb, 300);
                    }
                }

                @Override
                public void fail() {
                    if(isResume&&handler!=null){
                        LogUtils.i("NfsActivity2 fail thumb");
                        handler.postDelayed(videoThumb, 300);
                    }
                }

            });
            thumb.setVideoPath(nfsPath);
            thumb.start(1);
        }
    }

    public String paserTime(long time) {
        DateFormat formatter = new SimpleDateFormat("mm:ss");
        Calendar calendar = Calendar.getInstance();
        calendar.setTimeInMillis(time);
        return formatter.format(calendar.getTime());
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == 100) {
            if (grantResults[0] == PackageManager.PERMISSION_GRANTED && permissions[0].equals(Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
                getVersion(VerFlag.MAIN);
            }
        }
    }

    private void initView() {
        thumb = (MyVideoView) findViewById(R.id.thumb);
        thumb.setOnCompletionListener(new IMediaPlayer.OnCompletionListener() {
            @Override
            public void onCompletion(IMediaPlayer mp) {

            }

            @Override
            public void onError() {
                toastTv.setVisibility(View.GONE);
            }
        });
        nfsTitle = (BaseTitle) findViewById(R.id.nfs_title);
        progressBar = (ProgressBar) findViewById(R.id.progress_bar);
        noFilesTv = (TextView) findViewById(R.id.noFiles_tv);
        refreshView = (SuperRefreshRecyclerView) findViewById(R.id.refresh_view);
        toastTv = (TextView) findViewById(R.id.toast_tv);
        bottomLocal = (LinearLayout) findViewById(R.id.bottom_local);
        selectAllLocal = (TextView) findViewById(R.id.selectAll_local);
        downloadTv = (TextView) findViewById(R.id.download_tv);
        deleteLocal = (TextView) findViewById(R.id.delete_local);
        cancelLocal = (TextView) findViewById(R.id.cancel_local);

        videoNfs = new Vector<>();

        manager = new GridLayoutManager(context, 2);
        refreshView.init(manager, this, this);
        deleteLocal.setOnClickListener(this);
        cancelLocal.setOnClickListener(this);
        downloadTv.setOnClickListener(this);
        selectAllLocal.setOnClickListener(this);
        refreshView.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
                super.onScrollStateChanged(recyclerView, newState);
                if (newState == RecyclerView.SCROLL_STATE_IDLE) {//停止时
                    first = manager.findFirstVisibleItemPosition();
                }
            }
        });
    }

    private void initAdapter() {
        LogUtils.i("NfsActivity2 initAdapter");
        nfsRefreshAdapter = new NfsRefreshAdapter(beanList, context);
        refreshView.setAdapter(nfsRefreshAdapter);
        refreshView.showData();
        refreshView.setRefreshEnabled(true);
        refreshView.setLoadingMoreEnable(true);
        nfsRefreshAdapter.setOnItemClickListener(new BaseRecyclerAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(View view, int position, long id) {
                if (!SportStatic.isGetFiles) {
                    if (isResume) {
                        toastTv.setText(R.string.device_syn);
                        toastTv.setVisibility(View.VISIBLE);
                        handler.postDelayed(new ToastHide(), 800);
                    }
                    return;
                }
                if (beanList == null || beanList.size() == 0) {
                    return;
                }
                if (position >= beanList.size()) {
                    return;
                }
                if (isEdit) {
                    boolean select = beanList.get(position).isSelect();
                    if (select) {
                        beanList.get(position).setSelect(false);
                    } else {
                        beanList.get(position).setSelect(true);
                    }
                    if(isResume){
                        nfsRefreshAdapter.notifyItemChanged(position);
                    }
                    return;
                }
                boolean isImage = NfsUtil.isImageFile(beanList.get(position).getFileName());
                boolean isVideo = NfsUtil.isVideoFile(beanList.get(position).getFileName());
                int flag = 0;
                if (isImage) {
                    if (beanList.get(position).getCachePath() == null) {
                        return;
                    }
                    ArrayList<FileBean> list = new ArrayList<>();
                    for (int i = 0; i < beanList.size(); i++) {
                        if (NfsUtil.isImageFile(beanList.get(i).getFileName()) && beanList.get(i).getCachePath() != null) {
                            list.add(beanList.get(i));
                            if (i == position) {
                                flag = list.size() - 1;
                            }
                        }
                    }
                    FileBeanAll all = new FileBeanAll();
                    all.setBeanList(list);
                    all.setFlag(1);
                    Gson gson = new Gson();
                    String json = gson.toJson(all);
                    Intent intent1 = new Intent(context, BigImageActivity.class);
                    intent1.putExtra("json", json);
                    intent1.putExtra("position", flag);
                    startActivityForResult(intent1, BaseFinal.NfsActivity);
                } else if (isVideo) {
                    Gson gson = new Gson();
                    String json = gson.toJson(beanList.get(position));
                    LogUtils.e("NfsActivity json = " + json);
                    Intent intent = new Intent(context, VideoActivity.class);
                    intent.putExtra("json", json);
                    startActivityForResult(intent, BaseFinal.NfsActivity);
                }

            }
        });
        nfsRefreshAdapter.setOnItemLongClickListener(new BaseRecyclerAdapter.OnItemLongClickListener() {
            @Override
            public boolean onItemLongClick(View view, int position, long id) {
                if (!SportStatic.isGetFiles) {
                    if (isResume) {
                        toastTv.setText(R.string.device_syn);
                        toastTv.setVisibility(View.VISIBLE);
                        handler.postDelayed(new ToastHide(), 800);
                    }
                    LogUtils.e("正在同步设备中");
                    return false;
                }
                nfsRefreshAdapter.setEdit(true);
                nfsRefreshAdapter.notifyDataSetChanged();
                bottomLocal.setVisibility(View.VISIBLE);
                isEdit = true;
                return false;
            }
        });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if(requestCode==BaseFinal.NfsActivity){
            BaseFinal.NfsActivityRequest = false;
        }
    }
}

